package xrpc

import (
	"context"
	"gitee.com/xiedongji/antgo/cpts/xlog"
	"google.golang.org/grpc"
	"runtime/debug"
	"time"
)

func LogUnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		st := time.Now()
		defer func() {
			if recoverError := recover(); recoverError != nil {
				xlog.Logger("grpc", "log").Error().Interface("recover", recoverError).Bytes("stack", debug.Stack()).Interface("req", req).Interface("resp", resp).Err(err).TimeDiff("runtime", time.Now(), st).Send()
			} else {
				xlog.Logger("grpc", "log").Info().Interface("req", req).Interface("resp", resp).Err(err).TimeDiff("runtime", time.Now(), st).Send()
			}
		}()
		resp, err = handler(ctx, req)
		return resp, err
	}
}

func AuthUnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		xlog.Logger("grpc", "log").Info().Str("method", info.FullMethod).Msg("AuthUnaryServerInterceptor")
		resp, err = handler(ctx, req)
		return resp, err
	}
}
